package org.jlambda.util;

import java.io.IOException;
import java.io.InputStream;

/**
 * C+P from a blog, but normal stuff.
 * @author unintentionalobjectretention
 *
 */
public class LimitedLengthInputStream extends InputStream {
    private InputStream stream;
    private long available;
    private long availableAtMark;

    public LimitedLengthInputStream(InputStream stream, long available) {
  this.stream = stream;
        this.available = available;
    }

    public int read() throws IOException {
        if (available > 0) {
            available--;
            return stream.read();
        }
        return -1;
    }

    public int read(byte b[], int off, int len) throws IOException {
        if (available > 0) {
            if (len > available) {
                len = (int) available;
            }
            int read = stream.read(b, off, len);
            if (read == -1) {
                available = 0;
            } else {
                available -= read;
            }
            return read;
        }
        return -1;
    }

    public long skip(long n) throws IOException {
        long skip = stream.skip(n);
        if (available > 0) {
            available -= skip;
        }
        return skip;
    }

    public void mark(int readlimit) {
        stream.mark(readlimit);
        availableAtMark = available;
    }

    public void reset() throws IOException {
        stream.reset();
        available = availableAtMark;
    }

    public boolean markSupported() {
        return true;
    }
}